package com.cloud.easy.im.argeement;

import com.alibaba.fastjson.JSON;
import com.cloud.easy.im.argeement.server.LoginResponse;
import com.cloud.easy.im.argeement.client.LoginInfo;
import com.cloud.easy.im.argeement.server.ErrorResponse;
import io.netty.buffer.ByteBuf;

import static com.cloud.easy.im.utils.ByteBufJsonConvert.bufToString;

/**
 * 协议结构实体工厂类
 *
 * @author wangjian
 * @version 0.1.0
 * @create 2020年09月03日6:31 下午
 */
public class AgreementFactory {

    public static <T> T parse(String dataContentOfAgreement, Class<T> clazz) throws Exception {
        return JSON.parseObject(dataContentOfAgreement, clazz);
    }

    public static LoginInfo parseLoginInfo(String dataContentOfAgreement) throws Exception {
        return parse(dataContentOfAgreement, LoginInfo.class);
    }

    public static String objecttoString(Object object) throws Exception {
        return JSON.toJSONString(object);
    }

    public static Agreement parseAgreement(ByteBuf msg) throws Exception {
        return parse(bufToString(msg), Agreement.class);
    }

    /**
     * 构建登陆后返回响应
     *
     * @param code
     * @param userId
     * @return
     */
    public static Agreement createLoginInfoResponse(byte code
            , String userId,Integer productCode) throws Exception {
        return new Agreement(AgreementType.S.FROM_SERVER_TYPE_OF_RESPONSE$LOGIN
                , objecttoString(new LoginResponse(code))
                , "0"
                , userId
                , productCode
        );
    }

    /**
     * 构建心跳包回包响应
     *
     * @param userId 客户端id
     * @param productCode 产品Code
     * @return
     */
    public static Agreement createKeepLiveResponse(String userId,Integer productCode) {
        return new Agreement(AgreementType.S.FROM_SERVER_TYPE_OF_RESPONSE$KEEP$ALIVE
                , null
                , "0"
                , userId
                ,productCode
        );
    }

    /**
     * 构建异常情况下响应
     *
     * @param errorCode
     * @param errorMsg
     * @param userId
     * @return
     */
    public static Agreement createPErrorResponse(int errorCode, String errorMsg, String userId, Integer productCode) throws Exception {
        return new Agreement(AgreementType.S.FROM_SERVER_TYPE_OF_RESPONSE$FOR$ERROR
                , objecttoString(new ErrorResponse((byte) errorCode, errorMsg)), "0", userId,productCode);
    }

    /**
     * 构建伪应答包，主要用于返回FingerPrint指纹id
     * @param fromUserId
     * @param toUserId
     * @param recievedMessageFingerPrint
     * @return
     */
    public static Agreement createRecivedBack(String fromUserId, String toUserId
            , String recievedMessageFingerPrint,Integer productCode)
    {
        return new Agreement(AgreementType.C.FROM_CLIENT_TYPE_OF_RECIVED
            , recievedMessageFingerPrint, fromUserId, toUserId,productCode);
    }

}
